package com.cumt.threeway.view.dialog;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.cumt.threeway.R;
import com.cumt.threeway.activity.LoginActivity;
import com.cumt.threeway.activity.RegisterActivity;
import com.cumt.threeway.util.ThreeWayData;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * Created by Jingjing.Hu on 2016/4/7.
 */
public class CheckCodeDialog extends DialogFragment implements View.OnClickListener {

    private Context mContext;
    private String mPhoneNum;
    private String mPassword;
    private String mUserName;
    private TextView mSendPhoneTextView;
    private TextView mReSendView;
    private TextView mTitleTextView;
    private EditText mCheckCodeEditText;
    private View mNextStepView;
    private View mDelView;
    private TimeCount mTimeCount;
    private RequestQueue queue;

    private Handler mHandler = new Handler();

    public static CheckCodeDialog newInstance(String phoneNum, String password, String userName) {
        CheckCodeDialog checkCodeDialog = new CheckCodeDialog();
        Bundle bundle = new Bundle();
        bundle.putString("phoneNum", phoneNum);
        bundle.putString("password", password);
        bundle.putString("userName", userName);
        checkCodeDialog.setArguments(bundle);
        return checkCodeDialog;
    }

    // 填写从短信SDK应用后台注册得到的APPKEY
    private static String APPKEY = "1222dc9897e50";
    // 填写从短信SDK应用后台注册得到的APPSECRET
    private static String APPSECRET = "2aec31543004b550113800853505ec5e";
    private EventHandler handler = new EventHandler() {
        public void afterEvent(int event, int result, Object data) {
            if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                // 提交验证码
                afterSubmit(result, data);
            } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                // 获取验证码成功后的执行动作
                // afterGet(result, data);
            }
        }

    };

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        Bundle bundle = getArguments();
        mContext = activity;
        mPhoneNum = bundle.getString("phoneNum");
        mPassword = bundle.getString("password");
        mUserName = bundle.getString("userName");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int styleNormal = DialogFragment.STYLE_NORMAL;
        int theme = android.R.style.Theme_Light_NoTitleBar_Fullscreen;
        setStyle(styleNormal, theme);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_check_code_layout, null, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        queue = Volley.newRequestQueue(mContext);
        mTitleTextView = (TextView) view.findViewById(R.id.find_password);
        if(!TextUtils.isEmpty(mUserName)) {
            mTitleTextView.setText(getResources().getString(R.string.register_message));
        }
        SMSSDK.initSDK(mContext, APPKEY, APPSECRET);
        SMSSDK.registerEventHandler(handler);
        SMSSDK.getVerificationCode("86", mPhoneNum);
        mTimeCount = new TimeCount(60000, 1000);
        mTimeCount.start();
        mSendPhoneTextView = (TextView) view.findViewById(R.id.tv_send_phone);
        mCheckCodeEditText = (EditText) view.findViewById(R.id.et_check_code);
        mReSendView = (TextView) view.findViewById(R.id.btn_resend);
        mNextStepView = view.findViewById(R.id.btn_next_step);
        mNextStepView.setAlpha(0.4f);
        mNextStepView.setClickable(false);
        mDelView = view.findViewById(R.id.btn_check_code_del);
        view.findViewById(R.id.tv_back).setOnClickListener(this);
        mReSendView.setOnClickListener(this);
        mNextStepView.setOnClickListener(this);
        mDelView.setOnClickListener(this);

        mSendPhoneTextView.setText(mContext.getResources().getString(R.string.send_alert, Long.parseLong(mPhoneNum)));
        mCheckCodeEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    mNextStepView.setAlpha(0.4f);
                    mNextStepView.setEnabled(false);
                    mDelView.setVisibility(View.GONE);
                } else {
                    mNextStepView.setEnabled(true);
                    mNextStepView.setAlpha(0.8f);
                    mDelView.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mReSendView.setClickable(false);
            mReSendView.setText("重新发送(" + millisUntilFinished / 1000 + "秒)");
            mSendPhoneTextView.setText(mContext.getResources().getString(R.string.send_alert, Long.parseLong(mPhoneNum)));
            setPhoneNumRed(mSendPhoneTextView);
        }

        @Override
        public void onFinish() {
            mReSendView.setText("重新发送");
            mReSendView.setClickable(true);
            mSendPhoneTextView.setText("请重新发送验证码");
        }
    }

    private void setPhoneNumRed(TextView textView) {
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(mContext.getResources().getColor(R.color.blue));
        SpannableStringBuilder volume4Builder = new SpannableStringBuilder(textView.getText().toString());
        volume4Builder.setSpan(colorSpan, 5, 16, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(volume4Builder);
    }

    private void afterSubmit(final int result, Object data) {
        ((Activity) mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    if (mContext instanceof LoginActivity) {
                        ((LoginActivity) mContext).goResetPwdFinishDialog(mPhoneNum);
                    } else if (mContext instanceof RegisterActivity) {
                        if (!TextUtils.isEmpty(mPhoneNum) && !TextUtils.isEmpty(mPassword) && !TextUtils.isEmpty(mUserName)) {
                            ThreeWayData.getInstance().addUserInfo(mPhoneNum, mPassword, false);
                            Toast.makeText(mContext, getResources().getString(R.string.register_success), Toast.LENGTH_SHORT).show();
                            ((RegisterActivity) mContext).goLoginActivity();
//                            StringRequest srPost = new StringRequest(Request.Method.POST, URLS.IP + "NetServlet/RegistData",
//                                    new Response.Listener<String>() {
//                                        @Override
//                                        public void onResponse(String response) {
//                                            String userRegister = response.toString();
//                                            if (("true\r\n").equals(userRegister)) {
//                                                ThreeWayUtil.getInstance().saveLoginAccount(mContext, mPhoneNum);
//                                                ThreeWayUtil.getInstance().showToast(mContext, getResources().getString(R.string.register_success));
//                                                mHandler.postDelayed(new Runnable() {
//                                                    @Override
//                                                    public void run() {
//                                                        ((RegisterActivity) mContext).goLoginActivity();
//                                                    }
//                                                }, 2000);
//                                            } else {
//                                                Toast.makeText(mContext, "注册失败", Toast.LENGTH_SHORT).show();
//                                            }
//                                        }
//                                    }, new Response.ErrorListener() {
//                                @Override
//                                public void onErrorResponse(VolleyError error) {
//                                }
//                            }) {
//                                // 当手机发送请求时，回调用getParams方法，拼请求
//                                @Override
//                                protected Map<String, String> getParams() throws AuthFailureError {
//                                    Map<String, String> map = new HashMap<String, String>();
//                                    map.put("telephone", mPhoneNum);
//                                    map.put("password", mPassword);
//                                    map.put("userName", mUserName);
//                                    return map;
//                                }
//                            };
//                            queue.add(srPost);
                        }
                    }
                } else {
                    Toast.makeText(mContext, "验证码错误", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    private String getEditContent(EditText editText) {
        return editText.getText().toString();
    }

    @Override
    public void onClick(View v) {
        if (v == null) {
            return;
        }
        switch (v.getId()) {
            case R.id.tv_back:
                dismiss();
                break;
            case R.id.btn_check_code_del:
                mCheckCodeEditText.setText("");
                break;
            case R.id.btn_resend:
                mTimeCount.start();
                SMSSDK.getVerificationCode("86", mPhoneNum);
                break;
            case R.id.btn_next_step:
                SMSSDK.submitVerificationCode("86", mPhoneNum, mCheckCodeEditText.getText().toString());
                break;
        }
    }
}
